import React, { useState, useEffect } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Chip,
  LinearProgress,
  Grid,
  IconButton,
  Tooltip,
} from '@mui/material';
import { Iconify } from 'src/components/iconify';
import { safeApiCall, getAuthHeader } from 'src/utils/api';

interface RuleStats {
  totalRules: number;
  activeRules: number;
  inactiveRules: number;
  totalExecutions: number;
  successExecutions: number;
  failedExecutions: number;
  lastExecutionTime: string;
  nextScheduledTime: string;
}

export function AutoAccountingRuleStats({ refreshTrigger }: { refreshTrigger: number }) {
  const [stats, setStats] = useState<RuleStats>({
    totalRules: 0,
    activeRules: 0,
    inactiveRules: 0,
    totalExecutions: 0,
    successExecutions: 0,
    failedExecutions: 0,
    lastExecutionTime: '',
    nextScheduledTime: '',
  });
  const [loading, setLoading] = useState(false);

  // 获取统计信息
  const fetchStats = async () => {
    try {
      setLoading(true);
      const result = await safeApiCall('/api/auto-accounting/stats', 'GET', null, getAuthHeader());
      
      if (result.success) {
        setStats(result.data.data || stats);
      }
    } catch (error) {
      console.error('Error fetching stats:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    // 只在refreshTrigger > 0时才自动加载，避免页面打开就执行
    if (refreshTrigger > 0) {
      fetchStats();
    }
  }, [refreshTrigger]);

  const successRate = stats.totalExecutions > 0 
    ? Math.round((stats.successExecutions / stats.totalExecutions) * 100) 
    : 0;

  const formatTime = (timestamp: string) => {
    if (!timestamp) return '未执行';
    return new Date(timestamp).toLocaleString('zh-CN');
  };

  return (
    <Card>
      <CardContent>
        <Box display="flex" justifyContent="space-between" alignItems="center" sx={{ mb: 2 }}>
          <Typography variant="h6">
            规则统计
          </Typography>
          <Tooltip title="刷新统计">
            <IconButton onClick={fetchStats} size="small" disabled={loading}>
              <Iconify icon="eva:refresh-fill" />
            </IconButton>
          </Tooltip>
        </Box>

        {loading ? (
          <LinearProgress sx={{ mb: 2 }} />
        ) : (
          <Box>
            {/* 规则数量统计 */}
            <Box sx={{ mb: 3 }}>
              <Typography variant="subtitle2" color="text.secondary" sx={{ mb: 1 }}>
                规则数量
              </Typography>
              <Grid container spacing={1}>
                <Grid item xs={4}>
                  <Box textAlign="center">
                    <Typography variant="h4" color="primary.main">
                      {stats.totalRules}
                    </Typography>
                    <Typography variant="caption" color="text.secondary">
                      总规则
                    </Typography>
                  </Box>
                </Grid>
                <Grid item xs={4}>
                  <Box textAlign="center">
                    <Typography variant="h4" color="success.main">
                      {stats.activeRules}
                    </Typography>
                    <Typography variant="caption" color="text.secondary">
                      启用中
                    </Typography>
                  </Box>
                </Grid>
                <Grid item xs={4}>
                  <Box textAlign="center">
                    <Typography variant="h4" color="warning.main">
                      {stats.inactiveRules}
                    </Typography>
                    <Typography variant="caption" color="text.secondary">
                      已禁用
                    </Typography>
                  </Box>
                </Grid>
              </Grid>
            </Box>

            {/* 执行统计 */}
            <Box sx={{ mb: 3 }}>
              <Typography variant="subtitle2" color="text.secondary" sx={{ mb: 1 }}>
                执行统计
              </Typography>
              <Box sx={{ mb: 1 }}>
                <Box display="flex" justifyContent="space-between" alignItems="center" sx={{ mb: 0.5 }}>
                  <Typography variant="body2">
                    总执行次数
                  </Typography>
                  <Typography variant="body2" color="primary.main">
                    {stats.totalExecutions}
                  </Typography>
                </Box>
                <Box display="flex" justifyContent="space-between" alignItems="center" sx={{ mb: 0.5 }}>
                  <Typography variant="body2">
                    成功次数
                  </Typography>
                  <Typography variant="body2" color="success.main">
                    {stats.successExecutions}
                  </Typography>
                </Box>
                <Box display="flex" justifyContent="space-between" alignItems="center" sx={{ mb: 1 }}>
                  <Typography variant="body2">
                    失败次数
                  </Typography>
                  <Typography variant="body2" color="error.main">
                    {stats.failedExecutions}
                  </Typography>
                </Box>
              </Box>
              
              {/* 成功率进度条 */}
              <Box sx={{ mb: 1 }}>
                <Box display="flex" justifyContent="space-between" alignItems="center" sx={{ mb: 0.5 }}>
                  <Typography variant="caption" color="text.secondary">
                    成功率
                  </Typography>
                  <Typography variant="caption" color="primary.main">
                    {successRate}%
                  </Typography>
                </Box>
                <LinearProgress
                  variant="determinate"
                  value={successRate}
                  sx={{
                    height: 6,
                    borderRadius: 3,
                    backgroundColor: 'grey.200',
                    '& .MuiLinearProgress-bar': {
                      borderRadius: 3,
                    },
                  }}
                />
              </Box>
            </Box>

            {/* 时间信息 */}
            <Box>
              <Typography variant="subtitle2" color="text.secondary" sx={{ mb: 1 }}>
                执行时间
              </Typography>
              <Box sx={{ mb: 1 }}>
                <Box display="flex" justifyContent="space-between" alignItems="center">
                  <Typography variant="caption" color="text.secondary">
                    上次执行
                  </Typography>
                  <Typography variant="caption">
                    {formatTime(stats.lastExecutionTime)}
                  </Typography>
                </Box>
              </Box>
              <Box>
                <Box display="flex" justifyContent="space-between" alignItems="center">
                  <Typography variant="caption" color="text.secondary">
                    下次计划
                  </Typography>
                  <Typography variant="caption" color="primary.main">
                    {formatTime(stats.nextScheduledTime)}
                  </Typography>
                </Box>
              </Box>
            </Box>

            {/* 状态指示器 */}
            <Box sx={{ mt: 2, pt: 2, borderTop: '1px solid', borderColor: 'divider' }}>
              <Box display="flex" gap={1} flexWrap="wrap">
                <Chip
                  label={`${stats.activeRules} 个规则启用中`}
                  color="success"
                  variant="outlined"
                  size="small"
                  icon={<Iconify icon="eva:checkmark-circle-fill" />}
                />
                {stats.inactiveRules > 0 && (
                  <Chip
                    label={`${stats.inactiveRules} 个规则已禁用`}
                    color="warning"
                    variant="outlined"
                    size="small"
                    icon={<Iconify icon="eva:alert-circle-fill" />}
                  />
                )}
                {stats.totalExecutions > 0 && (
                  <Chip
                    label={`成功率 ${successRate}%`}
                    color={successRate >= 80 ? 'success' : successRate >= 60 ? 'warning' : 'error'}
                    variant="outlined"
                    size="small"
                    icon={<Iconify icon="eva:trending-up-fill" />}
                  />
                )}
              </Box>
            </Box>
          </Box>
        )}
      </CardContent>
    </Card>
  );
}
